package com.demo.springmvc.Dao;

import com.demo.springmvc.entities.Department;
import com.demo.springmvc.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Repository
public class EmployeeDao {

    private static Map<Integer, Employee> employeeMap;

    @Autowired
    private DepartmentDao departmentDao;

    static {
        employeeMap = new HashMap<>();
        employeeMap.put(1001, new Employee(1001, "AA", "aa@email.com", "M", new Department(101, "研发部")));
        employeeMap.put(1002, new Employee(1002, "BB", "bb@email.com", "W", new Department(102, "财务部")));
    }

    private int initId = 1003;

    // 增 / 改
    public void save(Employee employee, int depId) {
        if (employee.getId() == null) {
            employee.setId(initId++);
        }
        employee.setDepartment(departmentDao.getDeparment(depId));
        employeeMap.put(employee.getId(), employee);
    }

    // 查
    public Collection<Employee> getAll() {
        return employeeMap.values();
    }

    public Employee getEmployee(int id) {
        return employeeMap.get(id);
    }

    // 删
    public void remove(int id) {
        employeeMap.remove(id);
    }
}
